%% Author : lichuang 
-module(echubby_quorum_listener).

% Listen to quorum peer connections and spawn quorum server

-include("echubby.hrl").
-include("quorum_peer_pb.hrl").
-export([start_link/0, init/0]).

start_link() ->
  {ok, spawn_link(?MODULE, init, [])}.

init() ->
  {ok, ServerInfo} = gen_server:call(echubby_quorum_manager, my_server_info),
  ?DEBUG_MSG("my server info:~p", [ServerInfo]),
  register(?MODULE, self()),
  [{_, _, Port}] = ServerInfo,
  case gen_tcp:listen(Port, [list,
			     {packet, 4},
			     {active, false},
			     {reuseaddr, true},
			     {nodelay, true},
			     {keepalive, true}]) of
    {ok, ListenSocket} ->
      accept(ListenSocket);
    {error, Reason} ->
      ?CRITICAL_MSG("Failed to open socket on port ~p: ~p",
	[{Port}, Reason])
  end.

accept(ListenSocket) ->
  case gen_tcp:accept(ListenSocket) of
    {ok, Socket} ->
      {ok, {Address, Port}} = inet:peername(Socket),
      ?DEBUG_MSG("accept connection from [~p:~p]~n", [Address, Port]);
    {error, Reason} ->
      ?ERROR_MSG("(~w) Failed TCP accept: ~w", [ListenSocket, Reason])
    end,
  accept(ListenSocket).
